<?php

/*
 * This file defines a single function: lp_self_url()
 *
 * This function calculates the URL of the current request.
 */

/* This function calculates the URL of the current request.
 *
 * Parameters:
 *  $include_args   Include the parameters of the request if this is TRUE.
 *
 * Returns:
 *  The absolute URL of the current request.
 */
function lp_self_url($include_args = TRUE)
{
  if($_SERVER['HTTPS'] == 'off' || !$_SERVER['HTTPS']) {
    /* $_SERVER['HTTPS'] contains 'off' or is empty if this isn't a https
     * request.
     */
    $https = FALSE;
  } else {
    $https = TRUE;
  }

  /* Begin with the protocol part. */
  if($https) {
    $url = 'https';
  } else {
    $url = 'http';
  }

  /* Add the host name. */
  $url .= '://' . $_SERVER['SERVER_NAME'];

  /* Add the port number if this is a non-standard port number. */
  $port = $_SERVER['SERVER_PORT'];
  if(($https == FALSE && $port != 80) || ($https == TRUE && $port != 443)) {
    $url .= ':' . $port;
  }

  $request_url = $_SERVER['REQUEST_URI'];

  /* Remove the query string from the request if $include_args is FALSE. */
  if(!$include_args) {
    /* Remove the query string from the request url (if it is included). */
    $pos = strpos($request_url, '?');
    if($pos != FALSE) {
      $request_url = substr($request_url, 0, $pos);
    }
  }

  /* Add the request url to the url. We assume that the request url begins
   * with '/'
   */
  $url .= $request_url;

  return $url;
}